<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 重载并扩展 Kohana_Pagination 类
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: pager.php 129 2012-04-05 02:17:24Z yellow.chow $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */
class Pager extends Kohana_Pagination implements Countable, IteratorAggregate
{

    /**
     * @var Database_Query_Builder_Select
     */
    protected $_select = NULL;

    /**
     * @var Database instance or name of instance
     */
    protected $_db = NULl;

    /**
     * Creates a new Pager object.
     *
     * @param   Database_Query_Builder_Select
     * @param   array  configuration
     * @param   mixed  Database instance or name of instance
     * @return  void
     */
    public function __construct(Database_Query_Builder_Select $select, array $config = array(), $db = NULL)
    {
        $this->_select = $select;

        $this->_db = $db;

        $config['total_items'] = $select->count_all($this->_db);

        // Overwrite system defaults with application defaults
        $this->config = $this->config_group() + $this->config;

        // Pagination setup
        $this->setup($config);
    }

    /**
     * 返回给 foreach 调用的接口
     *
     * @return ArrayObject
     */
    public function getIterator()
    {
        return $this->_select->limit($this->items_per_page)->offset($this->offset)->execute($this->_db);
    }

    /**
     * 返回 count 函数获得的值
     *
     * @return int
     */
    public function count()
    {
        return $this->total_items;
    }

}